package com.backend.controller.user;

import cn.hutool.core.util.StrUtil;
import com.backend.service.user.UserService;
import com.common.constant.MessageConstant;
import com.common.exception.LoginException;
import com.common.result.Result;
import com.common.threadlocal.UserLocal;
import com.pojo.dto.LoginDTO;
import com.pojo.dto.RegisterDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;
    @PostMapping("/login")
    public Result login(@RequestBody LoginDTO loginDTO) {
        //TODO 责任链
        if (UserLocal.getCurrentUserDTO() != null) {
            throw new LoginException(MessageConstant.USER_HAS_LOGIN);
        }
        if (StrUtil.isBlank(loginDTO.getUsername()) || StrUtil.isBlank(loginDTO.getPassword())) {
            throw new LoginException(MessageConstant.LOGIN_PARAMS_NOT_ALL);
        }
        Map<String, String> map = new HashMap<>();
        map.put("token", userService.login(loginDTO));
        return Result.success(map);
    }
    @GetMapping("/me")
    public Result me() {
        return Result.success(userService.me());
    }
    @PostMapping("/logout")
    public Result logout() {
        userService.logout();
        return Result.success("登录退出成功");
    }
    @PostMapping("/sendMail")
    public Result sendMail(@RequestBody RegisterDTO registerDTO) {
        userService.sendMail(registerDTO);
        return Result.success("验证码发送成功");
    }
    @PostMapping("/register")
    public Result register(@RequestBody RegisterDTO registerDTO) {
        userService.register(registerDTO);
        String username = registerDTO.getUsername();
        String password = registerDTO.getPassword();
        LoginDTO loginDTO = new LoginDTO();
        loginDTO.setPassword(password);
        loginDTO.setUsername(username);
        return Result.success(userService.login(loginDTO));
    }
}
